package kr.hkit.powerjava.chapter15;

import java.awt.BorderLayout;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import java.util.Random;

import javax.imageio.ImageIO;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;

import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;

public class MyImageFrame1 extends JFrame implements ActionListener {
	BufferedImage img;
	private int pieces = 4;
	private int totalPiecs = pieces * pieces;
	private int[] pieceNumber;
	JPanel jp1 = new JPanel();
	
	public MyImageFrame1() {
		setTitle("Image Draw Test");
		try {
			img = ImageIO.read(new File("Koalat.jpg"));
		} catch (IOException e) {
			e.printStackTrace();
			System.exit(0);
		}
		
		pieceNumber = new int[totalPiecs];
		for(int i = 0; i<totalPiecs;i++){
			pieceNumber[i]=i;
		}
		
		getContentPane().add(new MyPanel1(), BorderLayout.CENTER);
//		add(jp1);
		
		JButton button = new JButton("DIVIDE");
		button.addActionListener(this);
		
		getContentPane().add(button, BorderLayout.SOUTH);
		setSize(600,600);
		setVisible(true);
	}	
	public void paint(Graphics g){
		g.drawImage(img, 0, 0, null);
	}
	
		void divide(){
			Random random = new Random();
			int ri;
			
			for(int i = 0; i < totalPiecs ; i++){
				ri = random.nextInt(totalPiecs);
				int temp = pieceNumber[i];
				pieceNumber[i] = pieceNumber[ri];
				pieceNumber[ri] = temp;
			}
		}
	class MyPanel1 extends JPanel{
		public void paitComponent(Graphics g){
			super.paintComponent(g);
			int pieceWidth = img.getWidth(null)/ pieces;
			int pieceHeight = img.getHeight(null)/ pieces;
			
			for(int x = 0; x < pieces; x++){
				int sx = x*pieceWidth;
			
				for(int y = 0; y < pieces; y++){
					int sy = y * pieceHeight;
					int number = pieceNumber[x * pieces + y	];
					int dx = (number / pieces) * pieceWidth;
					int dy = (number % pieces) * pieceHeight;
					g.drawImage(img, dx, dy, dx + pieceWidth, dy + pieceHeight, sx, sy, sx + pieceWidth, sy + pieceHeight, null);
				}
			}
		}
	}
	
	public static void main(String[] args) {
		new MyImageFrame1();
	}
	
	
	public void actionPerformed(ActionEvent e) {
		divide();
		repaint();
	}
}
